package com.gtpickupapp;

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.*;


import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SignUp extends Activity{
	
	public AlertDialog.Builder badUserName,badPassword,badNames;
	
	
	@Override  
	 public void onBackPressed() {  
		 //MyEventsGroup.group.back();
		 Intent myintent = new Intent(SignUp.this, gtpickupapp.class);
		 SignUp.this.startActivity(myintent);
		 finish();
	     return;  
	 } 
	
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.signup);
	 
	        final Button cancel = (Button) findViewById(R.id.cancelSignup);
	        cancel.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
	        cancel.setOnClickListener(new View.OnClickListener() {
	        	public void onClick(View v) {
	        		Intent myintent = new Intent(SignUp.this, gtpickupapp.class);
	        		SignUp.this.startActivity(myintent);
	        		finish();
	        		
	        	}         
	        });
	        
	        final Button submit = (Button) findViewById(R.id.signup);
	        submit.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
	        submit.setOnClickListener(new View.OnClickListener() {
	        	public void onClick(View v) {
	        		// Perform action on click
	        		boolean validUser = checkUsername();
	        		String result = "";
	        		InputStream is = null;
	        		
	        		//get information from the text fields
	        		EditText username = (EditText) findViewById(R.id.txt_username1);
	        		String uName = username.getText().toString().trim();
	        		
	        		EditText password1 = (EditText) findViewById(R.id.txt_password1);
	        		String pass1 = password1.getText().toString().trim();
	        		
	        		EditText password2 = (EditText) findViewById(R.id.txt_password2);
	        		String pass2 = password2.getText().toString().trim();
	        		
	        		EditText first_name = (EditText) findViewById(R.id.txt_firstname1);
	        		String fName = first_name.getText().toString().trim();
	        		
	        		EditText last_name = (EditText) findViewById(R.id.txt_lastname1);
	        		String lName = last_name.getText().toString().trim();
	        		
	        		//create the alert dialogs for the errors
	        		setupAlerts();
	        		
	        		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        		nameValuePairs.add(new BasicNameValuePair("userName",uName));
	        		nameValuePairs.add(new BasicNameValuePair("password",pass1));
	        		nameValuePairs.add(new BasicNameValuePair("firstName",fName));
	        		nameValuePairs.add(new BasicNameValuePair("lastName",lName));
	        		
	        		//only insert the new user if the username is not in use and it is not a space 
	        		if(validUser && (!uName.equals(""))){
	        			if( !pass1.equals("") && pass1.equals(pass2)){
			        		if( !fName.equals("") && !lName.equals("")){
		        				//http post
				        		try{
				        			//TODO add username to the bundle and redirect them to the home screen!
				        		        HttpClient httpclient = new DefaultHttpClient();
				        		        HttpPost httppost = new HttpPost("http://gtplay.webatu.com/signup.php");
				        		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        		        HttpResponse response = httpclient.execute(httppost);
				        		        HttpEntity entity = response.getEntity();
				        		        is = entity.getContent();
				        		        
				        		        //code to redirect on successful signup
				        		        Bundle bundle = new Bundle();
				                		bundle.putString("uName", uName);	
				                		bundle.putString("name",fName + " " + lName );
				                		Intent myintent = new Intent(SignUp.this,ProfilePage.class);
				                		myintent.putExtras(bundle);
				                		SignUp.this.startActivity(myintent);
				                		finish();
				                		//end of redirect code
				                		
				        		}catch(Exception e){
				        		        Log.e("log_tag", "Error in http connection "+e.toString());
				        		}
			        		}else{
			        			badNames.create().show();
			        		}
		        		 }else{
		        			 password1.setText("");
		        			 password2.setText("");
		        			 badPassword.create().show();
		        		 }
	        		
	        		}else{
	        			username.setText("");
	        			badUserName.create().show();
	        		}
	        		
	        	}         
	        });
	        
	        //make the dialog to get the user to insert in all of the needed info
	        LayoutInflater inflater = getLayoutInflater();
	        View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
	        ImageView image = (ImageView) layout.findViewById(R.id.image);
	        image.setImageResource(R.drawable.runner);
	        TextView text = (TextView) layout.findViewById(R.id.text);
	        String warningText = "User Information will not be viewable by other users, please insert correct information so we can locate the best matches";
	        text.setText(warningText);
	        
	        Toast toast = new Toast(getApplicationContext());
	        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	        toast.setDuration(Toast.LENGTH_LONG);
	        toast.setView(layout);
	        toast.show();
	 }
	 
	 /**
	  * Check to make sure the username is not already in use
	  * 
	  * @return boolean true if not in use
	  */
	 public boolean checkUsername(){
		boolean invalidlogin = false;
		EditText username = (EditText) findViewById(R.id.txt_username1);
		String result = "";
 		InputStream is = null;
 		String uname = username.getText().toString();
 		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 		nameValuePairs.add(new BasicNameValuePair("userName" ,uname));
 		//http post
 		try{
 				
 		        HttpClient httpclient = new DefaultHttpClient();
 		        HttpPost httppost = new HttpPost("http://gtplay.webatu.com/checkusername.php");
 		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 		        HttpResponse response = httpclient.execute(httppost);
 		        HttpEntity entity = response.getEntity();
 		        is = entity.getContent();
 		}catch(Exception e){
 		        Log.e("log_tag", "Error in http connection "+e.toString());
 		}
 		
 		//convert response to string
 		try{
 		        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
 		        StringBuilder sb = new StringBuilder();
 		        String line = null;
 		        while ((line = reader.readLine()) != null) {
 		                sb.append(line + "\n");
 		        }
 		        is.close();
 		 
 		        result=sb.toString();
 		}catch(Exception e){
 		        Log.e("log_tag", "Error converting result "+e.toString());
 		}
 		 
 		//parse json data
 		try{
 				//make sure the length is equal to 1. Meaning that the user is valid
 		        JSONArray jArray = new JSONArray(result);
 		        if(jArray.length() == 1){
 		        	invalidlogin = true;
 		        }
 		        
 		}
 		catch(JSONException e){
 		        Log.e("log_tag", "Error parsing data "+e.toString());
 		}
 		
 		
 		//if valid then allow user to register with this user name
 		if(invalidlogin){
 			return false;
 		}else{
 			return true;
 		}
 		
		
		 
	 }
	 
	 public void insertUser(){
		 
	 }
	 
	 public void setupAlerts(){
		 badUserName = new AlertDialog.Builder(this);
	        badUserName.setMessage("Sorry that is an invalid Username please try a different one")
	        	.setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		 
	        badPassword = new AlertDialog.Builder(this);
	        badPassword.setMessage("Sorry the passwords either do not match or are invalid")
	        	.setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
	        
	        badNames = new AlertDialog.Builder(this);
	        badNames.setMessage("Please complete the rest of the fields")
	        	.setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
	        
	 }
	
	//TODO Below was a test to pass information from one activity to another
		//can do this with a bundle 
		//Bundle bundle = getIntent().getExtras();
		//String username = bundle.getString("uName");
		//Toast.makeText(SignUp.this,username , 3).show();
		
		
}
